<?php
/**
 * beimuaihui System
 * Copyright(c) 2011-2020 beimuaihui.
 * @license    http://www.gnu.org/licenses/gpl.html     This software Under GPL V3 License 
 * beimuaihui@gmail.com
 * http://code.google.com/p/beimuaihui/
 * $Id: Model.php 473 2012-02-15 03:23:12Z beimuaihui $
 */


Zend_Loader::loadClass("Baogg_Db_Table");

//class Permission extends Baogg_Db_Table {
class Model  extends Baogg_Db_Table {
	/**
	 * The default table name 
	 */
	protected $_name;
	protected $_db ;
	protected $_primary; 
	
	function __construct() {
		$this->_name =   'model';
		
		$this->myPrimary= $this->_primary='model_id';
		parent::__construct();
	}
	
	

	/*
	 * Get All by state
	 */	
	

	/*
	 * Get category list unless a category . defaut is unless english
	 */
	
	
	
	
	 

	
	

	
     
	

	function getSame($arr) {	
		$ret=array();
		
		$where=array(" model_name ='{$arr['model_name']}'");
		if(isset($arr[$this->myPrimary])){
			$where[]=" $this->myPrimary !='{$arr[$this->myPrimary]}'";
		}
	    $sql = "SELECT {$this->myPrimary} FROM {$this->_name} WHERE  ".implode(" and ",$where);
	    
		//var_dump($arr);var_dump($this->myPrimary); echo $sql;exit;
		$rs = $this->_db->query($sql)->fetchAll();
		foreach((array)$rs as $v)
		{
		    $ret[]=$v[$this->myPrimary];
		}
		return $ret; 	
	
	}
	
    
    
    
    function changeTable($old,$new){
    	
    	try{
    	   $this->_db->query("desc ".$this->db_prefix."$old");
    	   $this->_db->query("RENAME TABLE ".$this->db_prefix."{$old} TO ".$this->db_prefix."{$new}");    	   
    	   
    	   return true;
    	}catch(Exception $e){
    		return false;
    	}
    }
    
    /**
     * 
     * generate model_field by existing table.column name
     * @param int $model_id
     */
    function initTable($model_id){
    	global $LANG;
    	
    	
    	$flag=true;
    	
    	Zend_Loader::loadClass("ModelField");
    	$ModelField=new ModelField();  
    	
    	if(!$model_id){
    		return false;
    	}
    	$rs_model=$this->getOne($model_id);    	
    	try{
    		$db_name='';    		
    		$class_name=self::tableNameToModel($rs_model[0]['table_name'],$rs_model[0]['db_key']);
    		//echo '<pre>';print_r($rs_model);var_dump(class_exists($class_name));
    		if(@class_exists($class_name)){
    			$instance=new $class_name();
    			/* $arr_config=$instance->getAdapter()->getConfig();
    			$db_name= $arr_config['dbname']; 
    			var_dump( $db_name);  	 */		
    		}else{
    			$flag=$this->genModelFile($model_id);
    			if($flag){
    				$instance=new $class_name();
    			}else{
    				$instance=$this;
    			}
    		}
    		$main_table=$instance->getAdapter()->query("desc ".$instance->db_prefix."{$rs_model[0]['table_name']}")->fetchAll();    		
    	}catch(Exception $e){    	
    		return true;
    	}
    	
    	Baogg_Language::loadFile($rs_model[0]['table_name']);
    	foreach($main_table as $v){
    		 //primary key must use in ext table
    		$field=array( 
				'model_id'=>$model_id, 
				'field_name'=>$v['Field'], 
				'show_name'=>BAOGG_LANGUAGE::get($v['Field']), 
				'field_type'=>$v['Type'], 
				'field_options'=>'', 
				'tips'=>'', 
				'check_pattern'=>'', 
				'check_error'=>'',			
				'model_pid'=>$model_id,
				'is_label'=>0,
				'is_basic'=>1, 
				'state'=>1, 
				'ordering'=>0,
				'init_value'=>is_null($v['Default'])?'':$v['Default'],
				'field_null'=>is_null($v['Null'])?'YES':$v['Null'],//$v['Null']
				'field_key'=>is_null($v['Key'])?'':$v['Key'],//$v['Key'],
				'field_extra'=>is_null($v['Extra'])?'':$v['Extra']//$v['Extra'],
    		);
    		
    		$existField=$ModelField->getList(array('model_id'=>$model_id,'field_name'=>$v['Field']));
    		if(!$existField){
    			$_flag=$ModelField->_insert($field);
    			$flag=$flag && $_flag;  
    		}
    		  		
    	}
    	
    
    	$this->genModelFile($model_id);
    	
    	
    	return $flag;
    }
    
    
    /**
     * 
     * generate table.column by model.model_field
     * @param int $model_id
     */
    public function genExtTable($model_id){
    	
    	$flag=true;
    	
    	Zend_Loader::loadClass("ModelField");
    	$ModelField=new ModelField();    	
    	
    	$rs_model=$this->getOne($model_id);
    	$rs_model_field=$ModelField->getList(array("model_id"=>(int)$model_id,"model_pid"=>(int)$model_id));    	
    	
    	if(!is_array($rs_model_field) || count($rs_model_field)<=0 || !$rs_model ||!is_array($rs_model)){
    		return true;
    	}
    	//echo '<pre>';print_r($rs_model);exit;
    	try{
    		
    		$db_name='';    		
    		$class_name=self::tableNameToModel($rs_model[0]['table_name'],$rs_model[0]['db_key']);
    		//echo '<pre>';print_r($rs_model);var_dump(class_exists($class_name));
    		if(class_exists($class_name)){
    			$instance=new $class_name();
    			/* $arr_config=$instance->getAdapter()->getConfig();
    			$db_name= $arr_config['dbname']; 
    			var_dump( $db_name);  	 */		
    		}else{
    			$flag=$this->genModelFile($model_id);
    			if($flag){
    				$instance=new $class_name();
    			}else{
    				$instance=$this;
    			}
    		}
    		$ext_table=$instance->getAdapter()->query("desc ".$instance->db_prefix."{$rs_model[0]['table_name']}")->fetchAll();   	
    		
    		
    		$arr_table_exist=array();
    		foreach($ext_table as $v){
    			$arr_table_exist[$v['Field']]=$v;
    		}
    	}catch(Exception $e){
    		$arr_table_exist=null;
    	}
    	
    	//$arr_field_type=include 'config/model/field_type.php';
    	$arr_field_type=include BAOGG_ROOT.'config/qa/field_type.php';
    	
    	$table=array();
    	/* 
    	foreach((array)$main_table as $v){
    		$table[$v['Field']]=$v;
    	}*/    		
    	foreach($rs_model_field as $v){
    		//if display field ,then return !isset($arr_field_type[$v['field_type']]['type']) || !$arr_field_type[$v['field_type']]['type']
    		if(!$v['field_type'] || !$v['field_name']){
    			continue;
    		}
    		$table[$v['field_name']]=array(
    			'Field'=>$v['field_name'],
    			'Key'  => $v['field_key'],
    			'Type' => @$arr_field_type[$v['field_type']]['type']?@$arr_field_type[$v['field_type']]['type']:$v['field_type'],
    			'Extra' =>$v['field_extra'],
    			'Default'=>$v['init_value'],
    			'Null'	=> $v['field_null']
    		);
    	}
    	
    	//echo __FILE__.__LINE__.'<pre>';print_r($table);print_r($arr_table_exist);exit;
    	$arr_sql=Baogg_Db::syncTable($this->db_prefix.$rs_model[0]['table_name'],$table,$arr_table_exist);
    	//echo __FILE__.__LINE__.'<pre>';print_r($table);print_r($arr_table_exist);print_r($arr_sql); exit;
    	foreach((array)$arr_sql as $sql){
    		$flag=$flag && $this->_db->query($sql);
    	}
    	
    	return $flag;
    	//$ModelField=
    	
    }
    
    /**
     * 
     * generate model's auto_increment pk
     * @param int $model_id
     */
    public function genExtPkTable($model_id){
    	$flag=true;
    	$ModelField=new ModelField();
    	$rs_model=$this->getOne($model_id);
    	if(!$rs_model){
    		return false;
    	}
    	$field=array(
    				'model_id'=>$model_id, 
    				'field_name'=>$rs_model[0]['table_name'].'_id', 
    				'show_name'=>BAOGG_LANGUAGE::get('id'), 
    				'field_type'=>'INT UNSIGNED', 
        			'field_view'=>'hidden',
    				'field_options'=>'', 
    				'tips'=>'', 
    				'check_pattern'=>'', 
    				'check_error'=>'', 
    				'model_pid'=>$model_id,
        			'is_label'=>0,    
    				'is_basic'=>0, 
    				'state'=>1, 
    				'ordering'=>0,
        			'init_value'=>'',
        			'field_null'=>'NO',
        			'field_key'=>'PRI',
        			'field_extra'=>'auto_increment'
    	);
    	$existField=$ModelField->getList(array('model_id'=>$field['model_id'],'model_pid'=>$field['model_id'],'field_name'=>$field['field_name']));
    	$existKey = $ModelField->getList(array('model_id'=>$field['model_id'],'model_pid'=>$field['model_id'],"field_key"=>'PRI'));
    	if(!$existField && !$existKey){
    		$flag=$flag && $ModelField->_insert($field);
    	}
    	return $flag;
    }
    
    
    public function genFile($model_id){
    	$flag=$this->genModelFile($model_id);
    	$flag=$this->genControllerFile($model_id) && $flag;
    	$flag=$this->genView($model_id) && $flag ;
    	return $flag;
    }
    
    
    public function genControllerFile($model_id){
    	$rs_model=$this->getOne($model_id);
    	
    	$Menu=new Menu();
    	$rs_menu=$Menu->getOne(@$rs_model[0]['menu_id']);
    	
    	if(!@$rs_menu[0]['url']){
    		return false;
    	}
    	
    	$arr_url=Baogg_Controller_Url::reverse($rs_menu[0]['url']);
    	$file_name=BAOGG_ROOT.'admin/'.ucwords($arr_url['module']).'/'.ucwords($arr_url['controller']).'Controller.php';
    	$backup_file_name=BAOGG_UPLOAD_DIR.'backup/admin/'.ucwords($arr_url['module']).'/'.ucwords($arr_url['controller']).'Controller'.'_'.date('YmdHis').'.php';
    	Baogg_File::mkdir(dirname($file_name));
    	Baogg_File::mkdir(dirname($backup_file_name));
    	if(file_exists($file_name)){
    		file_put_contents($backup_file_name, file_get_contents($file_name));
    	}
    	
    	$arr_Lang=array();
    	$lang_file=BAOGG_UPLOAD_DIR.'language/'.BAOGG_LANGUAGE.'/'.BAOGG_MDB_PREFIX.$arr_url['controller'].".php";
    	$backup_lang_file=BAOGG_UPLOAD_DIR.'backup/language/'.BAOGG_LANGUAGE.'/'.BAOGG_MDB_PREFIX.$arr_url['controller'].date('YmdHis').".php";
    	Baogg_File::mkdir(dirname($lang_file));
    	Baogg_File::mkdir(dirname($backup_lang_file));
        if(is_file($lang_file)){
        	//var_dump($lang_file);exit;
            $arr_Lang=include $lang_file;
            file_put_contents($backup_lang_file, file_get_contents($lang_file));
        }
        
    	$content='<?php    	
class '.ucwords($arr_url['module']).'_'.ucwords($arr_url['controller']).'Controller extends Baogg_Controller_Action {

	function init() {}
    function listAction() {
		
		global $LANG;
		$params=$this->getRequest()->getParams();
		$form_url=$params;
		Zend_Loader::loadClass("Baogg_View_Extgrid");';
    	
    	//$model_id=(int)$this->getRequest()->getParam("model_id");
    	
    	$rs_model=$this->getOne($model_id);
    	$form_height=$rs_model[0]['form_height']?$rs_model[0]['form_height']:300;
    	$arr_model_detail=$this->getModelAndField($model_id);
    	$instance=new $arr_model_detail['class_name'];
    	$key_field=$arr_model_detail['key_col'];
    	$lable_field=$arr_model_detail['label_col'];
    	$parent_field=isset($arr_model_detail['parent_col'])?$arr_model_detail['parent_col']:'';
    	
    	
    	if(!$model_id || !$rs_model){
	    	return false;
    	}
    	$ModelField=new ModelField();
    	$rs_model_field=$ModelField->getList(array("model_id"=>$model_id,"model_pid"=>$model_id,'state'=>1),array('ordering'=>'asc'));
    	
    	
    	$content.='
    	$Dict=new Dict();
		//echo __FILE__.__LINE__."<pre>";print_r($rs_model_field);exit;
		$form_url["action"]="combo";
		$str_combo_url=Baogg_Controller_Url::generate($form_url);';
    	
    	$form_content='';
    	foreach ( ( array ) $rs_model_field as $v ) {
    		if ($v ['is_basic']) {
    			$arr_Lang[$v ['field_name']]= $v ['show_name'];
    			$content.='
    			$cm ["'.$v ['field_name'].'"] = array ("sortable" => true);';
    			if($v['field_name']==$key_field){
    				$content.=
    				'$cm ["'.$v ['field_name'].'"]["cmType"]=Baogg_View_Extgrid::CMTYPE_PK;';
    			}
    			if ($v ['dict_id'] && in_array ( $v ['field_view'], array ('combo', 'radiogroup', 'checkgroup' ) )) {
    				$content.=
    				'$cm ["'.$v ['field_name'].'"] ["xtype"] = "templatecolumn";
    				$cm ["'.$v ['field_name'].'"] ["tpl"] = "{' . $v ['field_name'] . '2}";
    				$cm ["'.$v ['field_name'] . '2"] = array ("hidden" => true );';
    			}
    		}
    	
    		if ($v ['field_view']) {
    			$arr_Lang[$v ['field_name']]= $v ['show_name'];
    			$form_content.='
    			$form_items ["'.$v ['field_name'].'"] = array ("xtype" => "'.$v ['field_view'].'" );';
    			if ($v ['dict_id'] && in_array ( $v ['field_view'], array ('radiogroup', 'checkboxgroup' ) )) {
    				$form_content.='
    				$form_items ["'.$v ['field_name'].'"] ["source"] = $Dict->getDictCombo ("'. $v ['dict_id'].'" );';
    			} else if ($v ['dict_id'] && in_array ( $v ['field_view'], array ('combo', 'itemselector' ) )) {
    				$form_content.='
    				$form_items ["'.$v ['field_name'].'"] ["store"] = $Dict->getDictCombo ("'. $v ['dict_id'].'" );';
    	
    			} else if ($v ['field_view'] == 'textfield') {
    				$form_content.='    			
    				$form_items ["'.$v ['field_name'].'"] = array ("xtype" => "combo", 
    						"hideTrigger" => true, "mode" => "remote", "queryMode" => "remote", "minChars" => 1,
    						 "valueField" => "'.$v ['field_name'].'", "displayField" => "'.$v ['field_name'].'", 
    						 "forceSelection" => false, 
    						 "allowBlank" => true, 
    						 "store" => new Zend_Json_Expr ( \'new Ext.data.JsonStore({root: "data",totalProperty: "count",idProperty: "' . $v ['field_name'] . '",remoteSort: true,fields: ["' . $v ['field_name'] . '"],autoLoad:true,proxy: new Ext.data.HttpProxy({type:"ajax",actionMethods: { create : "POST", read : "POST", update : "POST", destroy: "POST" }, reader: {	 type: "json", 	 totalProperty: "count", root: "data"},url: "\'.$str_combo_url.\'model_field_id/' . $v ['field_id'] . '/"})})\' ), "pageSize" => Baogg_View_Extgrid::$PAGE_SIZE );';
    			}
    			
    		}
    	
    	}
    	
    	$content.='
    	$form_url ["action"] = "data";
    	$grid = new Baogg_View_Extgrid ( $form_url, $cm );
    	$grid->setSelectionModel ( false );
    	$grid->setRowNumberer ( true );
    	$grid->addExistButtons ( array ("add",  "query" ), array ("edit", "delete" ) );//"remove",';
    	
    	$content.='
    	$form_url ["action"] = "add";
    	$form = new Baogg_View_Extform ( array ("url" => $form_url, "height" => '.$form_height.', "width" => 600 ) );
    	'.$form_content.'
    	$form->addItems ( $form_items );
    	$form->addExistButtons ( array ("-", "save_grid", "save_new", "save", "-", "search", "-", "cancel" ) );
    	
    	
    	
    	$this->view->form = $form;
    	
    	$this->view->LANG = Zend_Json::encode ( $LANG );
    	$this->view->grid = $grid->render ();
    	}';
    	
    	$content.='
    	function dataAction() {
		$params = $this->getRequest ()->getParams ();
		';
		//$model_id = ( int ) $params ["model_id"];
		$Model = new Model ();
		$arr_model_detail = $Model->getModelAndField ( $model_id );
		
		
		$content.='
		$instance = new '.$arr_model_detail ['class_name'] .'();
		$where = array ();
		$order = array ();
		$limit = array ();
		foreach ( ( array ) $params as $k => $v ) {
			if ($k == "start" || $k == "limit") {
				$limit [$k] = $v;
			} else if ($k == "sort" || $k == "dir") {
				$order [$k] = $v;
			} else {
				if ($k == $instance->myPrimary) {
					if ($v && is_numeric ( $v )) {
						$v = ( int ) $v;
						$where [$k] = $v;
					}
				} else {
					$v = "%" . $v . "%";
					$where [$k] = $v;
				}
			
			}
		}
		
		$rs = $instance->getList ( $where, $order, $limit );';
		
		$ModelField = new ModelField ();
		$rs_model_field = $ModelField->getList ( array ("model_id" => $model_id, "model_pid" => $model_id,'dict_id>0',"field_view in ('combo','radiogroup','checkgroup','itemselector')" ), array ('ordering' => 'asc' ) );
		$arr_model_field = array ();
		foreach ( ( array ) $rs_model_field as $v ) {
			$arr_model_field [$v ['field_name']] = $v['dict_id'];
		}
		
		$content.='
		$Dict = new Dict ();
		$arr_dict = array ();
		foreach ( ( array ) $rs as $k => $v ) {';
			foreach((array)$arr_model_field as $col=>$dict_id){
				$content.='if(isset($v["'.$col.'"])){
					if (! isset ( $arr_dict ["'.$dict_id.'"] )) {
						$rs_dict = $Dict->getDictCombo ( "'.$dict_id.'" );
						$arr_dict ["'.$dict_id.'"] = array ();
						foreach ( $rs_dict as $v_dict ) {
							$arr_dict ["'.$dict_id.'"] [$v_dict [0]] = $v_dict [1];
						}
					}
					if (isset ( $arr_dict ["'.$dict_id.'"] [$v["'.$col.'"]] )) {
						$rs [$k] ["'.$col.'2"] = $arr_dict ["'.$dict_id.'"] [$v["'.$col.'"]];
					}
				}
				';
			}			
		$content.='}
		
		$rs_cnt = $instance->getList ( $where, null, NULL, "count(*) as cnt" );
		
		echo Zend_Json::encode ( array ("count" => $rs_cnt [0] ["cnt"], "data" => $rs ) );
		$this->_helper->viewRenderer->setNoRender ();
	
	}';
		$content.='
		function addAction() {
		$this->saveAction ();
	}
	
	function editAction() {
		$this->saveAction ();
	}
	
	function deleteAction() {
		
		$ret = array ("success" => false, "msg" => "delete_fail" );
		$id = Baogg_Controller_Action::_getParam ( "ids" );
		
	
		$instance = new '.$arr_model_detail ['class_name'] .'();
		
		if ($instance->_delete ( $id )) {
			$ret ["success"] = true;
			$ret ["msg"] = "delete_ok";
		}
		
		echo Baogg_Language::outputResult ( $ret );
		$this->_helper->viewRenderer->setNoRender ();
	}
	
	function removeAction() {
		$this->deleteAction ();
	}
	
	/**
	 * The save action
	 */
	function saveAction() {
		//global $LANG;
		

		$ret = array ("success" => false, "msg" => "save_fail" );
		
		//check form
		if (! $this->_request->isPost ()) {
			echo Baogg_Language::outputResult ( $ret );
			exit ();
		}
		
		$formData = $this->_request->getPost ();
		
		if (! $formData) {
			echo Baogg_Language::outputResult ( $ret );
			exit ();
		}
		
		
		$instance = new '.$arr_model_detail ['class_name'] .'();
		
		$arr = $instance->filterForm ( $formData );
		$action = $this->getRequest ()->getParam ( "action" );
		$rs = $instance->getSame2 ( $arr, " and " );
		if ($action == "edit") {
			if (count ( $rs ) == 0 || count ( $rs ) == 1 && $rs [0] == $arr ["role_id"]) {
				$instance->_update ( $arr, $arr [$instance->myPrimary] );
				$ret ["success"] = true;
				$ret ["msg"] = "save_ok";
			} else {
				$ret ["msg"] = "exist_same_record";
			}
		
		} else {
			//insert record
			//$permission_type = 1;
			if ($rs) {
				$ret ["msg"] = "exist_same_record";
			} else {
				unset ( $arr [$instance->myPrimary] );
				$ret ["success"] = $instance->_insert ( $arr ) > 0 ? true : false;
				$ret ["msg"] = "add_ok";
			}
		}
		
		echo Baogg_Language::outputResult ( $ret );
		
		$this->_helper->viewRenderer->setNoRender ();
	
	}
		}';
		
		
		file_put_contents($file_name,$content);
		
		$str_lang=var_export($arr_Lang,true);
		file_put_contents($lang_file, '<?php return '.$str_lang.'; ?>');
		
		return true;
    }
    

    public function genView($model_id){
    	$rs_model=$this->getOne($model_id);
    	
    	$Menu=new Menu();
    	$rs_menu=$Menu->getOne(@$rs_model[0]['menu_id']);
    	
    	if(!@$rs_menu[0]['url']){
    		return false;
    	}
    	$arr_url=Baogg_Controller_Url::reverse($rs_menu[0]['url']);
    	
    	$file=BAOGG_ROOT.'views/admin/'.strtolower ($arr_url['module']).'/'.strtolower ($arr_url['controller']).'_'.strtolower ($arr_url['action']).'.tpl';
    	$back_file=BAOGG_UPLOAD_DIR.'backup/'.'views/admin/'.strtolower ($arr_url['module']).'/'.strtolower ($arr_url['controller']).'_'.strtolower ($arr_url['action']).'.tpl';
    	Baogg_File::mkdir(dirname($file));
    	Baogg_File::mkdir(dirname($back_file));
    	
    	if(file_exists($file)){
    		file_put_contents($back_file,file_get_contents($file) );
    	}
    	
    	file_put_contents($file,file_get_contents(BAOGG_ROOT.'views/admin/system/menu_list.tpl'));
    	return true;
    }
    
    /**
     * 
     * No testing yet
     * @param unknown_type $model_id
     */
    public function genModelFile($model_id){
    	
    	
    	$arr_model_field=$this->getModelAndField($model_id);
    	//echo '<pre>';print_r($arr_model_field);exit;
    	if(isset($arr_model_field['class_name']) && isset($arr_model_field['key_col'])){
    		$arr_class_name=explode('_',$arr_model_field['class_name']);
    		if(count($arr_class_name)>=2){
    			$db_prefix=$arr_class_name[0];
    			$file_name=$arr_class_name[1];
    		}else{
    			$db_prefix='';
    			$file_name=$arr_class_name[0];
    		}
    		$file_name=BAOGG_ROOT . 'models/'.($db_prefix?$db_prefix.'/':'').$file_name.'.php';
    		if(file_exists($file_name)){
    			$backup_file=BAOGG_UPLOAD_DIR.'backup/models/'.($db_prefix?$db_prefix.'/':'').$arr_model_field['class_name'].'_'.date('YmdHis').'.php';
    			Baogg_File::mkdir(dirname($backup_file));
    			file_put_contents($backup_file, file_get_contents($file_name));
    		}
    		Baogg_File::mkdir(dirname($file_name));
    		file_put_contents($file_name, '<?php
    				class '.$arr_model_field['class_name'].'  extends Baogg_Db_Table'.($db_prefix?'_'.$db_prefix:'').' {
    		
    				protected $_name;
    				protected $_db ;
    				protected $_primary;
    		
    				function __construct() {
    				$this->_name =   "'.$arr_model_field['table_name'].'";
    		
    				$this->primary= $this->_primary="'.@$arr_model_field['key_col'].'";
    				parent::__construct();
    		}
    		}');
    		return true;
    	}else{
    		return false;
    	}
    	
    	
    }
    
    public function getModelAndField($model_id){
    	$ret=array('cols'=>array());
    	
    	$rs_model=$this->getOne($model_id);
    	$ret['table_name']=$rs_model[0]['table_name'];
    	$ret['class_name']=self::tableNameToModel($rs_model[0]['table_name'],$rs_model[0]['db_key']);
    	
    	$ModelField=new ModelField();
    	$rs_model_field=$ModelField->getList(array('model_id'=>$model_id,'model_pid'=>$model_id));
    	$key_col='';$label_col='';$parent_col='';
    	foreach($rs_model_field as $v){
    		if($v['field_key']=='PRI'){
    			$ret['key_col']=$v['field_name'];
    		}else if($v['is_label']){
    			$ret['label_col']=$v['field_name'];
    		}else if($v['is_value']){
    			$ret['value_col']=$v['field_name'];
    		}else if($v['is_parent']){
    			$ret['parent_col']=$v['field_name'];
    		}else{
    			$ret['cols'][]=$v['field_name'];
    		}
    	}
    	$ret['key_col']=isset($ret['key_col'])?$ret['key_col']:'id'; //default is id
    	$ret['value_col']=isset($ret['value_col'])?$ret['value_col']:$ret['key_col'];
    	return $ret;
    }
    
    public function getModelList($model_id,$filter=array(),$sorting=array(),$limit=array()){
    	$Model=new Model();
    	$arr_model_detail=$Model->getModelAndField($model_id);
		$instance=new $arr_model_detail['class_name'];
		if(!isset($arr_model_detail['parent_col'])){			
			$arr_model_detail['parent_col']=new Zend_Db_Expr('0 as pid');
		}
		
		$rs=$instance->getListTree($filter,$sorting,$limit,array_merge(array($arr_model_detail['value_col'],$arr_model_detail['label_col'],$arr_model_detail['parent_col']),$arr_model_detail['cols']));
    	if($limit){
			$rs_cnt=$instance->getList($filter,array(),array(),array('count(*) as cnt'));
			$count=$rs_cnt[0]['cnt'];
    	}else{
    		$count=count($rs);
    	}
		return array("count"=>$count,"data"=>$rs);
    }
    public function getModelCombo($model_id,$filter=array(),$sorting=array(),$limit=array()){
    	$ret=$this->getModelList($model_id,$filter=array(),$sorting=array(),$limit=array());
    	$data=$ret['data'];
    	$arr=array();
    	foreach((array)$data as $v){
    		if(!isset($cols)){
    			$cols=array_keys($v);
    		}
    		$arr[]=array($v[$cols[0]],$v[$cols[1]]);
    	}
    	return $arr;
    }
    
    public static function tableNameToModel($table_name,$schema=''){
    	$class_name="";
    	if($schema){
    		$class_name.=ucwords(str_replace("_"," ",$schema)).'_';
    	}
    	$class_name.=ucwords(str_replace("_"," ",$table_name));
    	$class_name=str_replace(" ","",$class_name);
    	return $class_name;
    }
    
    
    
}
